import 'dart:async';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/models/register/SchoolUserInfo.dart';
import 'package:ichinesereader/models/register/createQuoteResult.dart';
import 'package:ichinesereader/models/register/paymentRecordDto.dart';
import 'package:ichinesereader/models/register/paymentRecordICR.dart';
import 'package:ichinesereader/models/register/priceResult.dart';
import 'package:ichinesereader/models/register/proficiencyLevel.dart';
import 'package:ichinesereader/models/register/purchaseRecord.dart';
import 'package:ichinesereader/models/register/paymentUserInfo.dart';
import 'package:ichinesereader/service/register.dart';
import '../models/register/paymentToken.dart';
import '../utils/log.dart';
import 'package:universal_html/html.dart' as uHtml;

class RegisterController extends GetxController with StateMixin<dynamic> {
  RegisterServiceProvider _registerServiceProvider =
      new RegisterServiceProvider();
  String _customerId = '';
  String _token = '';
  String planId = '';
  String get getCustomerId => this._customerId;
  String get getToken => this._token;
  String get getPlanId => this.planId;
  PaymentUserInfo get getUserInfo => this.userInfo;
  List<PurchaseRecord> purchaseRecordItems = [];
  PaymentUserInfo userInfo = new PaymentUserInfo();
  List<ProficiencyLevel> levels = [];
  Rx<String> sampleText = ''.obs;
  Rx<int> levelIndex = 0.obs;

  //@override
  void onInit() {
    super.onInit();
  }

  @override
  dispose() {
    super.dispose();
  }

  setPlanId(planId) {
    this.planId = planId;
  }

  setUserInfo(PaymentUserInfo userInfo) {
    this.userInfo = userInfo;
  }

  void setLevelText(index) {
    levelIndex.value = index ?? 0;
    sampleText.value = levels[index].sampleText ?? '';
    change(levelIndex, status: RxStatus.success());
    change(sampleText, status: RxStatus.success());
  }

  Future<void> getPaymentToken(PaymentUserInfo userInfo) async {
    var token = PaymentToken();
    try {
      var response = await _registerServiceProvider
          .getPaymentToken(paymentUserInfoToJson(userInfo));
      if (response.statusCode == 200) {
        token = paymentTokenFromJson(response.bodyString);
        _customerId = token.customerId ?? '';
        _token = token.clientToken ?? '';
        //userInfo.customerId = token.customerId;
        userInfo.braintreeCustomerId = token.customerId;
        if (GetPlatform.isWeb) {
          uHtml.document.cookie = "clientToken=${token.clientToken};path=/";
          uHtml.document.cookie = "planId=${this.planId};path=/";
          uHtml.document.cookie = "customerId=${token.customerId};path=/";
        } else {
          CookieManager cookieManager = CookieManager.instance();
          final expiresDate =
              DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

          await cookieManager.setCookie(
            url: WebUri.uri(Uri.parse(Constants.BaseURL)),
            name: "clientToken",
            value: _token,
            domain: Constants.BaseDomain,
            path: '/',
            expiresDate: expiresDate,
            isSecure: true,
          );

          if (this.planId.isNotEmpty) {
            await cookieManager.setCookie(
              url: WebUri.uri(Uri.parse(Constants.BaseURL)),
              name: "planId",
              value: this.planId,
              domain: Constants.BaseDomain,
              path: '/',
              expiresDate: expiresDate,
              isSecure: true,
            );
          }

          await cookieManager.setCookie(
            url: WebUri.uri(Uri.parse(Constants.BaseURL)),
            name: "customerId",
            value: _customerId,
            domain: Constants.BaseDomain,
            path: '/',
            expiresDate: expiresDate,
            isSecure: true,
          );
        }
      }
    } catch (error) {
      Log.debug(error);
    }
  }

  void createIndividual(String customerId) async {
    try {
      userInfo.extendFlag = false;
      userInfo.customerId = customerId;
      var response = await _registerServiceProvider.createIndividual(
          paymentUserInfoToJson(userInfo), true);
      if (response.statusCode == 200) {}
    } catch (error) {
      Log.debug(error);
    }
  }

  Future<PaymentRecordIcr?> getPaymentRecordICRList() async {
    PaymentRecordIcr paymentRecordList = PaymentRecordIcr();
    try {
      var response = await _registerServiceProvider.getPaymentRecordICRList();
      if (response.statusCode == 200) {
        paymentRecordList = paymentRecordIcrFromJson(response.bodyString);
      }
    } catch (error) {
      Log.debug(error);
    }
    return paymentRecordList;
  }

  Future<PriceData> calculatePrice(
      int studentNumber, int paymentTerm, String zipCode) async {
    var _priceData = new PriceData();
    try {
      var response = await _registerServiceProvider.calculatePrice(
          studentNumber, paymentTerm, zipCode);
      if (response.statusCode == 200) {
        var data = priceResultFromJson(response.bodyString);
        if (data.result != null) {
          _priceData = data.result!;
        }
      }
    } catch (error) {
      Log.debug(error);
    }
    return _priceData;
  }

  Future<bool> isEmailAvailable(String email) async {
    var result = false;
    try {
      var response = await _registerServiceProvider.isEmailAvailable(email);
      result = response;
    } catch (error) {
      Log.debug(error);
    }
    return result;
  }

  Future<CreateQuoteData> createPaymentRecord(PaymentRecordDto dto) async {
    var result = new CreateQuoteData(id: "", quoteNumber: "");
    try {
      EasyLoading.show();
      var response = await _registerServiceProvider.createPaymentRecord(dto);
      if (response.statusCode == 200) {
        var res = createQuoteResultFromJson(response.bodyString);
        if (res.status == 1000) {
          return res.result!;
        }
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return result;
  }

  Future<SchoolUserInfoPayment> getPaymentReocord(String recordId) async {
    var result = new SchoolUserInfoPayment();
    try {
      EasyLoading.show();
      var response = await _registerServiceProvider.getPaymentRecord(recordId);
      if (response.statusCode == 200) {
        var res = schoolUserInfoFromJson(response.bodyString);
        if (res.status == 1000) {
          if (res.result != null && res.result!.payment != null) {
            return res.result!.payment!;
          }
        }
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return result;
  }

  Future<void> getProficiencyLevel() async {
    //List<ProficiencyLevel> levels = [];
    try {
      var response = await _registerServiceProvider.getProficiencyLevel();
      if (response.statusCode == 200) {
        var res = proficiencyLevelFromJson(response.bodyString);
        levels = res;
        sampleText.value = levels[0].sampleText ?? '';
        change(sampleText, status: RxStatus.success());
      }
    } catch (error) {
      Log.debug(error);
    }
    //return levels;
  }
}
